package com.hank.jms.message;

import com.hank.common.Constant;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.Enumeration;

public class SenderMessage {

    public static void main(String[] args) {
        //1、创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Constant.BROKER_URL);
        Connection connection = null;
        try {
            //2、通过工厂获取一个连接
            connection = connectionFactory.createConnection();
            //3、启动连接
            connection.start();
            //4、通过连接创建一个会话,并默认设开启事务,自动确认消息
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //5、通过会话构建一个目的地
            Destination destination = session.createQueue("my-test-queue");

            TemporaryQueue temporaryQueue=session.createTemporaryQueue();
            //Destination destination = session.createTopic("my-test-topic");
            //6、再通过session创建一个消息发送者，并设定发送目的地对象
            MessageProducer messageProducer = session.createProducer(destination);

            for (int i = 0; i < 3; i++) {
                TextMessage message = session.createTextMessage("This is TextMessage >>" + i);
//                MapMessage message= session.createMapMessage();
//                message.setString("text","This is MapMessage >>" + i);

                //自定义消息头
                message.setJMSType("MyJMSType");
                message.setJMSReplyTo(temporaryQueue);
                //自定义消息属性
                message.setStringProperty("username","Hank");
                message.setStringProperty("address","Guangzhou");
                //特性消息属性
//                message.setStringProperty("JMSXGroupID","testGP");
//                message.setIntProperty("JMSXGroupSeq",2);
//                message.setJMSPriority(9);//这个设置不管用,bug
                //7、发送JMS消息
//                messageProducer.send(message,DeliveryMode.NON_PERSISTENT,8,3000);
                messageProducer.send(message);


            }
            session.commit();
            //8、关闭所有资源
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
